<?php

$start_time = microtime();

require_once("languages/pl/head.php");

require_once('includes/sessions.php');
require_once ('libs/Smarty.class.php');
require_once ('includes/config.php');
require_once('class/player_class.php');

$smarty = new Smarty;
$smarty-> compile_check = true;
$smarty -> cache_dir = 'cache';
$smarty -> template_dir = './templates';
$smarty -> compile_dir = './templates_c';

$ADODB_CACHE_DIR = '/cache';


/**
* Errors reporting level
*/
error_reporting(E_ALL);

/**
* function to catch errors and write it to bugtrack
*/

function catcherror($errortype, $errorinfo, $errorfile, $errorline) 
{
}

/**
* set catching errors
*/
set_error_handler('catcherror');

$smarty -> assign (array("Gamename" => $gamename, 
	"Gameadress" => $gameadress));

if (isset ($_POST['pass'])) 
{
    if (!$_POST['email'] || !$_POST['pass']) 
    {
        $smarty -> assign (array("Error" => EMPTY_LOGIN, 
            "Meta" => ''));
        $smarty -> display ('error.tpl');
        exit;
    }
    $pass = MD5($_POST['pass']);
    $strEmail = $db -> qstr($_POST['email'], get_magic_quotes_gpc());
    $query = $db -> Execute("SELECT `id`, `user`, `email`, `rank`, `freeze` FROM `players` WHERE `email`=".$strEmail." AND `pass`='".$pass."'");
    $logres = $query -> RecordCount();

    /**
     * Check for ban
     */
    $banned = false;
    $arrBans = array('IP', 'ID', 'nick', 'mailadres');
    $arrAmount = array($_SERVER['REMOTE_ADDR'], $query -> fields['id'], $query -> fields['user'], $query -> fields['email']);
    $i = 0;
    foreach ($arrBans as $strBan)
    {
        $objBan = $db -> Execute("SELECT `type` FROM `ban` WHERE `type`='".$strBan."' AND `amount`='".$arrAmount[$i]."'");
        if ($objBan -> fields['type'])
        {
            $banned = true;
            $objBan -> Close();
            break;
        }
        $i ++;
    }
    if ($banned) 
    {
        $smarty -> assign (array("Error" => BANNED, 
                                 "Meta" => ''));
        $smarty -> display ('error.tpl');
        exit;
    }
    if ($logres <= 0) 
    {
        $smarty -> assign (array("Error" => E_LOGIN, 
                                 "Meta" => ''));
        $smarty -> display ('error.tpl');
        exit;
    } 
        else 
    {
        $intCtime = time() - 180;
        $objQuery = $db -> Execute("SELECT count(*) FROM `players` WHERE `rank`!='Admin' AND rank!='Staff' AND `lpv`>=".$intCtime);
        $numo = $objQuery -> fields['count(*)'];
        $objQuery -> Close();
        if ($numo >= $pllimit && $query -> fields['rank'] != 'Admin' && $query -> fields['rank'] != 'Staff' && $query -> fields['rank'] != "KrĂłlewski BĹ‚azen") 
        {
            $smarty -> assign(array("Error" => MAX_PLAYERS, 
                                    "Meta" => ''));
            $smarty -> display('error.tpl');
            exit;
        }
        if ($query -> fields['freeze'])
        {
            $smarty -> assign(array("Error" => ACCOUNT_BLOCKED.$query -> fields['freeze'].ACCOUNT_DAYS,
                                    "Meta" =>  ''));
            $smarty -> display('error.tpl');
            exit;
        }
        $_SESSION['email'] = $_POST['email'];
        $_SESSION['pass'] = $_POST['pass'];
        $db -> Execute("UPDATE players SET logins=logins+1, rest='N' WHERE email=".$strEmail."");
        $objFight = $db -> Execute("SELECT `fight`, `strength`, `agility`, `inteli`, `wytrz`, `szyb`, `wisdom` FROM `players` WHERE `email`=".$strEmail);
        if ($objFight -> fields['fight'])
        {
            $intNumber = rand(0, 5);
            $arrValues = array($objFight -> fields['strength'], $objFight -> fields['agility'], $objFight -> fields['inteli'], $objFight -> fields['wytrz'], $objFight -> fields['szyb'], $objFight -> fields['wisdom']);
            $arrStats = array('strength', 'agility', 'inteli', 'wytrz', 'szyb', 'wisdom');
            $intLost = ($arrValues[$intNumber] / 20);
            $db -> Execute("UPDATE `players` SET `hp`=0, `fight`=0, ".$arrStats[$intNumber]."=".$arrStats[$intNumber]."-".$intLost." WHERE `email`=".$strEmail);
		$db -> Execute("UPDATE `players` SET `exp`=`exp`-100 WHERE `exp`>99 AND `email`=".$strEmail);
        }
        $objFight -> Close();
        $query -> Close();
    }
}

// koniec sesji
if (empty($_SESSION['email']) || empty($_SESSION['pass'])) 
{
        $smarty -> assign (array("Error" => E_SESSIONS, 
                                 "Meta" => ''));
        $smarty -> display ('error.tpl');
        exit;
}

//data i czas
//date_default_timezone_set('Etc/GMT');
date_default_timezone_set('Europe/Warsaw');
$time = date("H:i:s");
$data = date("y-m-d");
$arrtemp = array($data, $time);
$newdate = implode(" ",$arrtemp);

//ladowanie gracza
$pass = MD5($_SESSION['pass']);

//$strEmail = $db -> qstr($_SESSION['email'], get_magic_quotes_gpc());
$stat = $db -> Execute("SELECT `id`, `lpv` FROM `players` WHERE `email`='".$_SESSION['email']."'");
if (!$stat -> fields['id']) 
{
    $smarty -> assign (array("Error" => E_PLAYER, 
                             "Meta" => ''));
    $smarty -> display ('error.tpl');
    exit;
}


$ctime = time();
$ip = $_SERVER['REMOTE_ADDR'];
$title = strip_tags($title);
if ($title) {
	$db -> Execute("UPDATE `players` SET `lpv`=".$ctime.", `ip`='".$ip."', `page`='".$title."' WHERE `id`=".$stat -> fields['id']);
} else {
	$db -> Execute("UPDATE `players` SET `lpv`=".$ctime.", `ip`='".$ip."' WHERE `id`=".$stat -> fields['id']);
}
if ($stat -> fields['lpv'] < time() - 420) $smarty->clear_cache('footera.tpl');
$player = new Player($stat -> fields['id']);
$stat -> Close();
$smarty -> assign (array ("Id" => $player -> id,
                          "Level" => $player -> level,
                          "Exp" => $player -> exp,
                          "Health" => $player -> hp,
                          "Maxhealth" => $player -> max_hp,
                          "Mana" => $player -> mana,
                          "Energy" => $player -> energy,
                          "Maxenergy" => $player -> max_energy,
                          "Gold" => $player -> credits,
                          "Bank" => $player -> bank,
                          "Mithril" => $player -> platinum,
                          "Style" => $player -> style,
                          "Graphbar" => $player -> graphbar));

//czy otwarta gra
$objOpen = $db -> Execute("SELECT `value` FROM `settings` WHERE `setting`='open'");
if ($objOpen -> fields['value'] == 'N' && $player -> rank != 'Admin') 
{
    $objReason = $db -> Execute("SELECT `value` FROM `settings` WHERE `setting`='close_reason'");
    $smarty -> assign (array("Error" => REASON."<br />".$objReason -> fields['value'], 
                             "Meta" => ''));
    $objReason -> Close();
    $smarty -> display ('error.tpl');
    exit;
}
$objOpen -> Close();


//$smarty -> display ('header.tpl');

/**
* Deklaracja funkcji error
*/
function error($text) 
{
    global $smarty;
    global $db;
    global $start_time;
    global $player;
    global $numquery;
    global $compress;
    global $sqltime;
    global $phptime;
    if (!ereg("<a href",$text)) 
    {
		$nazwapliku= substr($_SERVER['PHP_SELF'],strrpos($_SERVER['PHP_SELF'],'/')+1);
        $text = $text." (<a href=\"".$nazwapliku."\">wróć</a>)";
    }
    $smarty -> assign(array("Message" => $text, 
                            "Meta" => ''));
    $smarty -> display ('error1.tpl');
    if (!$_GET['ajax']) require_once("includes/foot.php");
    exit;
}

/**
 * Function check for integer overflow in forms
 */ 
function integercheck($strField)
{
    $intStrlen = strlen($strField);
    if ($intStrlen > 15)
    {
        error(ERROR);
    } 
}

/**
* Delete session when player escape from fight
*/
$arrTitle = array('Arena Walk', 'Labirynt', 'Portal', 'Astralny plan');
$arrLocations = array('Altara', 'Ardulith', 'Port', 'Portal', 'Astralny plan');
if ($player -> fight != 0 && (!in_array($title, $arrTitle)) && (in_array($player -> location, $arrLocations))) 
{
    $db -> Execute("UPDATE `players` SET `hp`=0, `fight`=0, `bless`='', `blessval`=0 WHERE `id`=".$player -> id) or die($db -> ErrorMsg());
    if (!isset($_SESSION['amount']))
    {
        $_SESSION['amount'] = 1;
    }
    for ($k = 0; $k < $_SESSION['amount']; $k ++) 
    {
        $strIndex = "mon".$k;
        unset($_SESSION[$strIndex]);
    }
    unset($_SESSION['exhaust'], $_SESSION['round'], $_SESSION['points'], $_SESSION['amount'], $_SESSION['dodge']);
    error (ESCAPE);
}

//anty-macro
if (!isset($_SESSION['time'])) $_SESSION['time'] = time();
$test = time() - $_SESSION['time'];
$_SESSION['time'] = time();
if ($test < 1)
{
	$db -> Execute("UPDATE players SET macro=macro+1 WHERE id=".$player -> id);
	if ($player -> macro >= 20)
	{
		$strDate = $db -> DBDate($newdate);
		$db -> Execute("INSERT INTO `log` (`owner`, `log`, `czas`) VALUES(1,'".$player -> user." ID: ".$player -> id." odswiezyl gra ponad 20 razy - macro', ".$strDate.")");
		error('Nie umiesz czytac? A moze uzywasz programu do odswiezania? Lepiej wymysl dobra wymowke, bo wiadomosc o twoich wyczynach zostala wyslana do Wladcy.');
	}
	if ($player -> macro > 10)
	{
		if ($player -> macro > 20) error('Nie umiesz czytac? A moze uzywasz programu do odswiezania? Lepiej wymysl dobra wymowke, bo wiadomosc o twoich wyczynach zostala wyslana do Wladcy.');
		error('Zbyt szybko i czesto odswiezasz, postaraj sie wolniej');
	}
} elseif ($player -> macro > 0)
{
	$db -> Execute("UPDATE players SET macro=0 WHERE id=".$player -> id);
}


/**
* Delete sessions variables when player exit forums
*/
if (isset($_SESSION['forums']) && !ereg("forums.php", $_SERVER['PHP_SELF']))
{
    unset($_SESSION['forums']);
}

if (isset($_SESSION['tforums']) && !ereg("tforums.php", $_SERVER['PHP_SELF']))
{
    unset($_SESSION['tforums']);
}

?>